/* eslint-disable no-console */
/* eslint-disable no-use-before-define */
/* eslint-disable no-return-assign */
/* eslint-disable array-callback-return */
/* eslint-disable no-redeclare */
/* eslint-disable no-new-object */
/* eslint-disable no-unused-vars */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable no-var */
/* eslint-disable no-restricted-properties */
/* eslint-disable radix */
/* eslint-disable no-param-reassign */
/* eslint-disable no-shadow */
/* eslint-disable eqeqeq */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-plusplus */
/* eslint-disable consistent-return */
import moment from 'moment';
import numeral from 'numeral';
import React from 'react';
import nzh from 'nzh/cn';
import { parse, stringify } from 'qs';
import FileSaver from 'file-saver';
import fetch from 'dva/fetch';
import axios from 'axios';
import { message } from 'antd';
import router from 'umi/router';
import { type } from 'os';
import md5 from 'js-md5';

// 数字格式转化
export function formatNumber(value) {
  if (value) {
    const formatString = value.toString();
    if (formatString.indexOf('.') > 0) {
      // 存在小数
      const values = formatString.split('.')[1].length;
      const result = new Array(values).fill(0).join('');
      return numeral(value).format(`0,0.[${result}]`);
    }
    return numeral(value).format(`0,0.00`);
  }
}

export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - day * oneDay;

    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
  }

  const year = now.getFullYear();
  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
}

export function getPlainNode(nodeList, parentPath = '') {
  const arr = [];
  nodeList.forEach(node => {
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

export function digitUppercase(n) {
  return nzh.toMoney(n);
}

function getRelation(str1, str2) {
  if (str1 === str2) {
    console.warn('Two path are equal!'); // eslint-disable-line
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
  }
  if (arr1.every((item, index) => item === arr2[index])) {
    return 2;
  }
  return 3;
}

function getRenderArr(routes) {
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
    // 去重
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
    // 是否包含
    const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path
  );
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
  const renderRoutes = renderArr.map(item => {
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
      exact,
      ...routerData[`${path}${item}`],
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}

export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

export function getQueryPath(path = '', query = {}) {
  const search = stringify(query);
  if (search.length) {
    return `${path}?${search}`;
  }
  return path;
}

/* eslint no-useless-escape:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export function isUrl(path) {
  return reg.test(path);
}

export function formatWan(val) {
  const v = val * 1;
  if (!v || Number.isNaN(v)) return '';

  let result = val;
  if (val > 10000) {
    result = Math.floor(val / 10000);
    result = (
      <span>
        {result}
        <span
          style={{
            position: 'relative',
            top: -2,
            fontSize: 14,
            fontStyle: 'normal',
            marginLeft: 2,
          }}
        >
          万
        </span>
      </span>
    );
  }
  return result;
}

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export function isAntdPro() {
  return window.location.hostname === 'preview.pro.ant.design';
}

// 数组拼接字符串
export function getArryStringBySymbol(array, key, symbol) {
  let str = '';
  for (let i = 0; i < array.length; i++) {
    str += array[i][key] + (symbol || ',');
  }
  // 去掉最后一个逗号(如果不需要去掉，就不用写)
  if (str.length > 0) {
    str = str.substr(0, str.length - 1);
  }
  return str;
}

// 判断有无重复
export function isRepeat(arr, id) {
  const hash = {};
  // eslint-disable-next-line guard-for-in
  for (const i in arr) {
    if (hash[arr[i][id]]) {
      return true;
    }
    hash[arr[i][id]] = true;
  }
  return false;
}

// 导出文件:默认从文件服务器下载模板
export default function downloadFile(
  params,
  url = '/csApi/fileServer/downloadFile',
  method = 'GET',
  callback
) {
  const newOptions = { credentials: 'include' };
  let newUrl = url;
  const currentTime = new Date().getTime();
  const userId = window.atob(window.localStorage.getItem(window.btoa('userId'))) || '';
  if (method === 'GET') {
    newUrl = encodeURI(`${url}?${stringify(params)}`);
    newOptions.headers = {
      'x-trace-log-id': `${currentTime}|${md5(currentTime + userId)} `,
    };
  }
  if (method === 'POST') {
    newOptions.headers = {
      Accept: '*/*',
      'Content-Type': 'application/json; charset=utf-8',
      'x-trace-log-id': `${currentTime}|${md5(currentTime + userId)} `,
      ...newOptions.headers,
    };
    newOptions.method = method;
    newOptions.body = JSON.stringify(params);
  }

  let fileName = (params && params.fileName) || null;
  return fetch(newUrl, newOptions)
    .then(response => {
      const contentType = response.headers.get('Content-Type');
      if (contentType && contentType.match(/application\/json/i)) {
        return response.json();
      }
      for (const entry of response.headers.entries()) {
        if (entry[0] == 'filename') {
          fileName = decodeURIComponent(entry[1]);
        }
      }
      return response.blob();
    })
    .then(blob => {
      if (!blob.successs && !blob.size) {
        return message.warning(`${blob.message || '下载失败！'}`);
      }
      FileSaver.saveAs(blob, fileName);
    })
    .then(() => {
      if (callback) callback();
    })
    .catch(err => {
      throw err;
    });
}

export function checkCardID(sId, success, error) {
  const aCity = {
    11: '北京',
    12: '天津',
    13: '河北',
    14: '山西',
    15: '内蒙古',
    21: '辽宁',
    22: '吉林',
    23: '黑龙江',
    31: '上海',
    32: '江苏',
    33: '浙江',
    34: '安徽',
    35: '福建',
    36: '江西',
    37: '山东',
    41: '河南',
    42: '湖北',
    43: '湖南',
    44: '广东',
    45: '广西',
    46: '海南',
    50: '重庆',
    51: '四川',
    52: '贵州',
    53: '云南',
    54: '西藏',
    61: '陕西',
    62: '甘肃',
    63: '青海',
    64: '宁夏',
    65: '新疆',
    71: '台湾',
    81: '香港',
    82: '澳门',
    91: '国外',
  };
  let iSum = 0;
  const reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9X]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/;
  if (!reg.test(sId)) return error ? error('你输入的身份证长度或格式错误') : null;
  sId = sId.replace(/X$/i, 'a');
  if (aCity[parseInt(sId.substr(0, 2))] == null) return error ? error('你的身份证地区非法') : null;
  const sBirthday = `${sId.substr(6, 4)}-${Number(sId.substr(10, 2))}-${Number(sId.substr(12, 2))}`;
  const d = new Date(sBirthday.replace(/-/g, '/'));
  if (sBirthday != `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`)
    return error ? error('身份证上的出生日期非法') : null;
  for (let i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
  if (iSum % 11 != 1) return error ? error('你输入的身份证号非法') : null;
  const info = `${aCity[parseInt(sId.substr(0, 2))]},${sBirthday},${
    sId.substr(16, 1) % 2 ? '1' : '2'
  }`; // 身份信息
  const sex = sId.substr(16, 1) % 2 ? '1' : '2'; // 性别
  success(sex, d, info);
}

export function compare(property){
  return function(a,b){
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
  }
}
// ----antd1.0：开始： csweb1.0 untils
// 封装自定义axios
export function cusAxios(interfaceUrl, inObject, reqMode) {
  var inObject = inObject || {};
  // let hostUrl = '/nmweb' //21
  const hostUrl = '/csApi'; // 48
  return new Promise((resolve, reject) => {
    axios(hostUrl + interfaceUrl, {
      method: reqMode || 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: JSON.stringify(inObject),
    })
      .then(response => {
        if (response.status == 200) {
          if (response.data.rspCode == '10000') {
            message.warning('登录会话超时,请重新登录！ ');
            router.replace('/user/login');
            return;
          }
          if (!response.data.success && response.data.rspCode == 'ERROR') {
            reject('response.data.rspCode：ERROR');
            const pattern = /[~!@#$%^&*()/\|,.<>?"'();:_+-=\[\]{}]/;
            return message.warning(response.data.message || '服务端未知错误！');
            // return pattern.test(response.data.message) ? message.error('服务端未知错误！') : message.warning(response.data.message || '服务端未知错误！')
          }
          resolve(response.data);
        } else {
          reject({ message: `${response.status}` });
        }
      })
      .catch(err => {
        reject({ message: '-1' });
      });
  });
}
// 解析参数
export function urlParse(url) {
  // let url = this.props.location.search;
  const obj = new Object();
  if (url.indexOf('?') != -1) {
    const str = url.substr(1);
    const strs = str.split('&');
    for (let i = 0; i < strs.length; i++) {
      obj[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
    }
  }
  return obj;
}

// 获取字典
export function getDictList(dictTypeList, callback, thenCallBack) {
  cusAxios('/mdm/nmDict/queryDictItemsByCodes', dictTypeList)
    .then(res => {
      if (res.success && res.data) {
        callback(res.data);
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    })
    .then(() => {
      if (thenCallBack) {
        thenCallBack();
      }
    })
    .catch(err => {
      console.log(err);
    });
}
export function getDictListOrder(dictTypeList) {
  return new Promise((resolve, reject) => {
    // cusAxios('/mdm/nmDict/queryDictItemsByCodes', { dictTypeList })
    cusAxios('/mdm/nmDict/queryDictItemsByCodes', dictTypeList)
      .then(res => {
        if (res.success && res.data) {
          resolve(res.data);
        } else {
          message.warning(`${res.message || '暂无数据！'}`);
        }
      })
      .catch(err => {
        console.log(err);
      });
  });
}
// 匹配字典
export function matchDict(list, id) {
  let dict = null;
  list.map(item => {
    if (item.itemCode == id) {
      return (dict = item.itemName);
    }
  });
  return dict;
}

// 根据地区areaId查找地区
export function byAreaIdGetArea(areaId) {
  return cusAxios('/mdm/baseService/loadNmArea', { areaId })
    .then(res => {
      if (res.success && res.data) {
        return res.data;
      }
    })
    .catch(err => {
      console.log(err);
    });
}
// 组装复选框字典
export function getcheckboxList(list) {
  const arr = [];
  list.map(item => {
    const obj = {};
    obj.label = item.itemName;
    obj.value = item.itemCode;
    arr.push(obj);
  });
  return arr;
}

// 下载模板
export function downloadTemplate(fileId, fileName) {
  const data = `fileId=${fileId}&fileName=${fileName}`;
  axios
    .get(
      encodeURI(encodeURI(`/csApi/fileServer/downloadFile?${data}`)),
      { responseType: 'arraybuffer' },
      { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
    )
    .then(res => {
      if (res.status == 200 && res.data) {
        const blob = new Blob([res.data], { type: 'application/msword;charset=UTF-8' });
        // for IE
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        }
        // for Non-IE (chrome, firefox etc.)
        else {
          const a = document.createElement('a');
          document.body.appendChild(a);
          a.style = 'display: none';
          const url = window.URL.createObjectURL(blob);
          a.href = url;
          a.download = fileName;
          a.click();
          a.remove();
          window.URL.revokeObjectURL(url);
        }
      } else {
        message.warning('下载出错！');
      }
    });
}

// 获取地区树形数据
export function transformTreeData(data) {
  // 属性配置信息
  const attributes = {
    value: 'areaId',
    label: 'areaName',
    areaNature: 'areaNature',
  };
  const resData = data;
  const tree = [];
  for (let i = 0; i < resData.length; i++) {
    if (resData[i].areaNature == 3 || resData[i].areaNature == 4) {
      const obj = {
        value: resData[i][attributes.value],
        label: resData[i][attributes.label],
        children: [],
      };
      tree.push(obj);
      resData.splice(i, 1);
      i--;
    }
  }
  run(tree);
  function run(chiArr) {
    if (resData.length !== 0) {
      for (let i = 0; i < chiArr.length; i++) {
        for (let j = 0; j < resData.length; j++) {
          if (chiArr[i].value === resData[j][attributes.areaId]) {
            const obj = {
              value: resData[j][attributes.value],
              label: resData[j][attributes.label],
              children: [],
            };
            chiArr[i].children.push(obj);
            resData.splice(j, 1);
            j--;
          }
        }
        run(chiArr[i].children);
      }
    }
  }
  return tree;
}

// os1.0版本util
// 封装自定义axios
export function osAxios(interfaceUrl, inObject) {
  var inObject = inObject || {};
  // let hostUrl = '/nmweb' //21
  const hostUrl = '/osApi'; // 48
  return new Promise((resolve, reject) => {
    axios(hostUrl + interfaceUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: JSON.stringify(inObject),
    })
      .then(response => {
        // console.log()
        if (response.status == 200) {
          if (response.data.rspCode == '10000') {
            message.warning('登录会话超时,请重新登录！ ');
            router.replace('/user/login');
            return;
          }
          resolve(response.data);
        } else {
          reject({ status: response.status });
        }
      })
      .catch(err => {
        reject({ status: -1 });
      });
  });
}

// //运行查询
// export function empSelect(value) {
//   return new Promise((resolve, reject) => {
//     osAxios('/insCardHdlOS/getEmpList', { empName: value })
//       .then(res => {
//         console.log('员工查询1111', res);
//         if (res.success == true) {
//           resolve(res.data);
//         } else {
//           reject(res.message);
//         }
//       })
//       .catch(err => {
//         console.log(err);
//       });
//   });
// }
// 自定义问题人员some方法
export function cusSome(arr, key, code) {
  return arr.some(item => item[key] == code);
}
/*
 * JSON数组去重
 * @param: [array] json Array
 * @param: [string] 唯一的key名，根据此键名进行去重
 */
export function uniqueArray(array, key) {
  const result = typeof array[0] === 'undefined' ? [] : [array[0]];
  for (let i = 1; i < array.length; i++) {
    const item = array[i];
    let repeat = false;
    for (let j = 0; j < result.length; j++) {
      if (item[key] == result[j][key]) {
        repeat = true;
        break;
      }
    }
    if (!repeat) {
      result.push(item);
    }
  }
  return result;
}
// //问题人员类型统一
// export function proTypeUnify() {
//   return new Promise((resolve, reject) => {
//     osAxios('/plcyDataDict/queryProbTypeList', {})
//       .then(res => {
//         console.log('类型', res);
//         if (res.success == true) {
//           resolve(res);
//         } else {
//           // message.error(res.message)
//           reject(res.message);
//         }
//       })
//       .catch(err => {
//         console.log(err);
//       });
//   });
// }
// //问题匹配字典
// export function matchProDict(list, id) {
//   let dict = null;
//   list.map(item => {
//     if (item['probTypeId'] == id) {
//       return (dict = item.probTypeName);
//     }
//   });
//   return dict;
// }
// 切割文件地址（不含C：\等前缀路径）
export function getFileName(obj) {
  if (obj) {
    const index = obj.lastIndexOf('\\');
    obj = obj.substring(index + 1, obj.length);
    return obj;
  }
}

// 封装文件导出
export function excelAxios(url, inParam) {
  // let url = '/osApi/insAddDet/exportInsAdd'
  axios
    .post(
      url,
      inParam,
      { responseType: 'arraybuffer' },
      { 'Content-Type': 'application/json;charset=UTF-8' }
    )
    .then(res => {
      const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=UTF-8' });
      const fileName = res.headers.filename;
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, `${fileName}.xls`);
      }
      // for Non-IE (chrome, firefox etc.)
      else {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = decodeURI(fileName);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }
    });
}
// esweb1.0 untils
// 封装自定义axios
export function esAxios(interfaceUrl, inObject) {
  var inObject = inObject || {};
  // let hostUrl = '/nmweb' //21
  const hostUrl = '/esApi'; // 48
  return new Promise((resolve, reject) => {
    axios(hostUrl + interfaceUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: JSON.stringify(inObject),
    })
      .then(response => {
        // console.log()
        if (response.status == 200) {
          if (response.data.rspCode == '10000') {
            message.warning('登录会话超时,请重新登录！ ');
            router.replace('/user/login');
            return;
          }
          resolve(response.data);
        } else {
          reject({ status: response.status });
        }
      })
      .catch(err => {
        reject({ status: -1 });
      });
  });
}
// 员工查询
export function empSelect(value) {
  return new Promise((resolve, reject) => {
    esAxios('/proveHdl/getEmpList', { empName: value })
      .then(res => {
        resolve(res);
        // if(res.success == true) {
        //  resolve(res.data);
        // } else {
        // //	 reject(res.message)
        // }
      })
      .catch(err => {
        // console.log(err)
      });
  });
}
export function proTypeUnify() {
  return new Promise((resolve, reject) => {
    esAxios('/plcyDataDict/queryProbTypeList', {})
      .then(res => {
        if (res.success == true) {
          resolve(res);
        } else {
          // message.error(res.message)
          reject(res.message);
        }
      })
      .catch(err => {
        console.log(err);
      });
  });
}
// 问题匹配字典
export function matchProDict(list, id) {
  let dict = null;
  list.map(item => {
    if (item.probTypeId == id) {
      return (dict = item.probTypeName);
    }
  });
  return dict;
}
// 员工新增校验
export function empVerify(url, objOparmes) {
  return new Promise((resolve, reject) => {
    esAxios(url, objOparmes)
      .then(res => {
        resolve(res);
      })
      .catch(err => {});
  });
}
// 导出
export function outExcelFun(url, objOparmes) {
  axios
    .post(
      url,
      objOparmes,
      { responseType: 'arraybuffer' },
      { 'Content-Type': 'application/json;charset=UTF-8' }
    )
    .then(res => {
      const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=UTF-8' });
      const fileName = res.headers.filename;
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, `${fileName}.xls`);
      }
      // for Non-IE (chrome, firefox etc.)
      else {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = decodeURI(fileName);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }
    });
}

// mgreweb1.0  untils
// 封装自定义axios
export function mgrAxios(interfaceUrl, inObject, reqMode) {
  var inObject = inObject || {};
  // let hostUrl = '/nmweb' //21
  const hostUrl = '/mgrApi'; // 48
  return new Promise((resolve, reject) => {
    axios(hostUrl + interfaceUrl, {
      method: reqMode || 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      xhrFields: { withCredentials: true },
      data: JSON.stringify(inObject),
    })
      .then(response => {
        if (response.status == 200) {
          if (response.data.rspCode == '10000') {
            message.warning('登录会话超时,请重新登录！ ');
            router.replace('/user/login');
            return;
          }
          resolve(response.data);
        } else {
          reject({ status: response.status });
        }
      })
      .catch(err => {
        console.log(err);
        reject({ status: -1 });
      });
  });
}
// 封装自定义axios
export function csAxios(interfaceUrl, inObject, reqMode) {
  var inObject = inObject || {};
  // let hostUrl = '/nmweb' //21
  const hostUrl = '/csApi'; // 48
  return new Promise((resolve, reject) => {
    axios(hostUrl + interfaceUrl, {
      method: reqMode || 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      xhrFields: { withCredentials: true },
      data: JSON.stringify(inObject),
    })
      .then(response => {
        if (response.status == 200) {
          if (response.data.rspCode == '10000') {
            message.warning('登录会话超时,请重新登录！ ');
            router.replace('/user/login');
            return;
          }
          resolve(response.data);
        } else {
          reject({ status: response.status });
        }
      })
      .catch(err => {
        console.log(err);
        reject({ status: -1 });
      });
  });
}
// 封装自定义axios
export function nsAxios(interfaceUrl, inObject, reqMode) {
  var inObject = inObject || {};
  // let hostUrl = '/nmweb' //21
  const hostUrl = '/nsApi'; // 48
  return new Promise((resolve, reject) => {
    axios(hostUrl + interfaceUrl, {
      method: reqMode || 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      xhrFields: { withCredentials: true },
      data: JSON.stringify(inObject),
    })
      .then(response => {
        if (response.status == 200) {
          if (response.data.rspCode == '10000') {
            message.warning('登录会话超时,请重新登录！ ');
            router.replace('/user/login');
            return;
          }
          resolve(response.data);
        } else {
          reject({ status: response.status });
        }
      })
      .catch(err => {
        console.log(err);
        reject({ status: -1 });
      });
  });
}

// ----antd1.0：结束： csweb1.0 untils

// 请求头统一加密：
export function requestHeadersMd5() {
  const userId = window.atob(window.localStorage.getItem(window.btoa('userId'))) || '';
  const currentTime = new Date().getTime();
  return { 'x-trace-log-id': `${currentTime}|${md5(currentTime + userId)} ` };
}

// 问题人员列表返回包保存数据
export function getProPagination(key, currentKey, pagination) {
  const temp = { ...pagination };
  if (key === currentKey) {
    const {
      problempage: {
        proPageData: {
          pagination: { current, pageSize },
        },
      },
      // eslint-disable-next-line no-underscore-dangle
    } = window.g_app._store.getState();
    temp.current = current;
    temp.currentPage = current;
    temp.pageSize = pageSize;
  }
  return temp;
}

/**
 * @description 递归深拷贝
 * @param obj
 * @returns {{}|Array}
 */
 export const getDeepCopy = (obj) => {
  let arrobj;
  Array.isArray(obj)?arrobj =[] :arrobj = {};
  for(const  i in obj){
    if(obj.hasOwnProperty(i)){
      arrobj[i] = (typeof obj[i] === "object" && !(obj[i] instanceof Date))&&(obj[i]!==null)? getDeepCopy(obj[i]) : obj[i];
    }
  }
  return arrobj;
};

/**
 * @description 求table的宽度及设置样式
 * @param arr
 * @returns {Array}
 * @param option
 * @returns {Object}
 * @param 是否重新复制一份
 * @returns {Boolean}
 */
 export const getDeepWidth = (arr, option={}, flagCopy=true, dataIndex = []) => {
  if(!Array.isArray(arr)) return arr
  arr.sort((a,b)=> a.itemOrder - b.itemOrder)
  const onColumns = flagCopy && getDeepCopy(arr) || arr
  const oWidth = option.width && +option.width || 0
  // YYYY-MM-DD
  const ymd = ['beginTime,']
  // YYYY-MM-DD HH:mm
  const ymdhm = ['operTime']

  const totalX = onColumns.reduce((total, {children, itemList, width, itemName, itemCode}, index)=>{
    // console.log(total,'0');

    const onWidth = width && +width || oWidth
    onColumns[index].title = itemName
    onColumns[index].dataIndex = [...dataIndex ,itemCode]
    const YMD = ymd.includes(itemCode)
    const YMDHM = ymdhm.includes(itemCode)
    YMD ||  YMDHM ? 
    onColumns[index].render = text =>
      text ? (
        <span style={{ minWidth: 60 }}>{moment(text).format(YMDHM ?'YYYY-MM-DD HH:mm': 'YYYY-MM-DD')}</span>
      ) : ('--') : ''
    onColumns[index].sorter = true
    
    itemList && (onColumns[index].children = itemList)
    itemList = null
    if(onColumns[index].children) {
      const item = getDeepWidth(onColumns[index].children, option, false, [...dataIndex, itemCode])
      onColumns[index].children = item.onColumns
      total += (item.totalX || 100)
      // console.log(total,'1');
    } else {
      total += (onWidth || 100)
      // console.log(total,'3');
      onColumns[index].onCell = () => ({ style: { textAlign: 'center', width: onWidth || '100px'} })
      onColumns[index].onHeaderCell = () => ({ style: { textAlign: 'center', width: onWidth || '100px' } })
      /**  !index && (onColumns[index].onCell = () => ({ style: { textAlign: 'center', width: onWidth || '100px', 'background': '#faad14', color: '#FFFFFF' } }))
      !index && (onColumns[index].onHeaderCell = () => ({ style: { textAlign: 'center', width: onWidth || '100px', 'background': '#faad14', color: '#FFFFFF' } }))
      */
    }

    return total
  }, 0)
  return {totalX, onColumns};
};
// 驼峰转大写 追加排序
export const toLoceUpCase = (text, order) => text && text.replace && `${text.replace(/([A-Z])/g,"_$1").toLocaleUpperCase()} ${order === 'descend'? 'desc' : 'asc'}`|| text
